<template>
  <div class="dashboard-container">
    <!-- 角色信息提示 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <div v-if="isAdmin" class="admin-info">
          <el-alert
            title="您当前以管理员身份登录，可以访问系统管理功能"
            type="success"
            :closable="false"
            effect="light"
          />
        </div>
        <div v-else-if="isInitiator" class="role-info">
          <el-alert
            title="您当前以发起人身份登录"
            type="info"
            :closable="false"
            effect="light"
          />
        </div>
        <div v-else-if="isContestant" class="role-info">
          <el-alert
            title="您当前以参赛者身份登录"
            type="info"
            :closable="false"
            effect="light"
          />
        </div>
      </el-col>
    </el-row>
    
    <!-- 功能概览 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon contest-icon"><TrendCharts /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ stats.contestCount }}</div>
              <div class="stat-label">可参与竞赛</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon ranking-icon"><Medal /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ stats.participatedCount }}</div>
              <div class="stat-label">已参与竞赛</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon score-icon"><DataAnalysis /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ stats.rankScore }}</div>
              <div class="stat-label">我的积分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon cert-icon"><Document /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ stats.certificateCount }}</div>
              <div class="stat-label">获得证书</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 近期竞赛 -->
    <el-row>
      <el-col :span="24">
        <div class="section-header">
          <h3>近期竞赛</h3>
          <el-button type="primary" plain size="small" @click="goToContestList">查看全部</el-button>
        </div>
        
        <el-table :data="recentContests" style="width: 100%" v-loading="loading">
          <el-table-column prop="title" label="竞赛名称" min-width="180" />
          <el-table-column prop="startTime" label="开始时间" width="160" :formatter="formatDate" />
          <el-table-column prop="currentParticipants" label="参与人数" width="100" align="center" />
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" link size="small" @click="viewContestDetail(scope.row.id)">
                查看
              </el-button>
              <el-button 
                v-if="canJoinContest(scope.row)" 
                type="success" 
                link 
                size="small" 
                @click="joinContest(scope.row.id)"
              >
                参与
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getContestList } from '@/api/contest'
import { 
  TrendCharts, 
  Medal, 
  DataAnalysis, 
  Document
} from '@element-plus/icons-vue'

export default {
  name: 'DashboardView',
  components: {
    TrendCharts,
    Medal,
    DataAnalysis,
    Document
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const recentContests = ref([])
    
    // 用户统计数据（示例数据）
    const stats = ref({
      contestCount: 0,
      participatedCount: 0,
      rankScore: 0,
      certificateCount: 0
    })

    // 从localStorage获取用户信息
    const userInfo = computed(() => {
      const userInfoStr = localStorage.getItem('userInfo')
      return userInfoStr ? JSON.parse(userInfoStr) : null
    })

    // 判断是否是管理员
    const isAdmin = computed(() => {
      return userInfo.value && userInfo.value.roleCode === 'ADMIN'
    })

    // 判断是否是发起人
    const isInitiator = computed(() => {
      return userInfo.value && userInfo.value.roleCode === 'INITIATOR'
    })

    // 判断是否是参赛者
    const isContestant = computed(() => {
      return userInfo.value && userInfo.value.roleCode === 'CONTESTANT'
    })
    
    // 获取近期竞赛
    const fetchRecentContests = async () => {
      loading.value = true
      try {
        const res = await getContestList({
          page: 1,
          size: 5,
          status: 1 // 进行中的竞赛
        })
        recentContests.value = res.data.records
        stats.value.contestCount = res.data.total
      } catch (error) {
        console.error('获取竞赛列表失败', error)
      } finally {
        loading.value = false
      }
    }
    
    // 模拟获取用户统计数据
    const fetchUserStats = () => {
      // 实际项目中这里应该调用API获取真实数据
      stats.value = {
        contestCount: 12,
        participatedCount: 5,
        rankScore: 320,
        certificateCount: 2
      }
    }
    
    // 格式化日期
    const formatDate = (row) => {
      if (!row.startTime) return '未设置'
      const date = new Date(row.startTime)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待审核'
        case 1: return '进行中'
        case 2: return '已拒绝'
        case 3: return '已取消'
        case 4: return '已结束'
        default: return '未知状态'
      }
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 0: return 'warning'
        case 1: return 'success'
        case 2: return 'danger'
        case 3: return 'info'
        case 4: return 'primary'
        default: return 'info'
      }
    }
    
    // 是否可以参与竞赛
    const canJoinContest = (contest) => {
      return contest.status === 1 && 
        (!contest.participantLimit || contest.currentParticipants < contest.participantLimit)
    }
    
    // 查看竞赛详情
    const viewContestDetail = (id) => {
      router.push(`/contest/detail/${id}`)
    }
    
    // 参与竞赛
    const joinContest = (id) => {
      router.push(`/contest/detail/${id}`)
    }
    
    // 进入竞赛广场
    const goToContestList = () => {
      router.push('/contest/list')
    }
    
    onMounted(() => {
      fetchRecentContests()
      fetchUserStats()
    })
    
    return {
      loading,
      recentContests,
      stats,
      isAdmin,
      isInitiator,
      isContestant,
      formatDate,
      getStatusText,
      getStatusType,
      canJoinContest,
      viewContestDetail,
      joinContest,
      goToContestList
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  .admin-info, .role-info {
    margin-bottom: 20px;
  }
  
  .dashboard-cards {
    margin-bottom: 20px;
    
    .stat-card {
      margin-bottom: 20px;
      border-radius: 8px;
      
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          font-size: 40px;
          margin-right: 15px;
          
          &.contest-icon {
            color: #409eff;
          }
          
          &.ranking-icon {
            color: #67c23a;
          }
          
          &.score-icon {
            color: #e6a23c;
          }
          
          &.cert-icon {
            color: #f56c6c;
          }
        }
        
        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
            line-height: 1.2;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h3 {
      margin: 0;
      color: #2c3e50;
      font-size: 18px;
    }
  }
}
</style> 